package itbour.onetouchshow.activity.challengezone.filter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTrimmer;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.video.cut.interfaces.TrimVideoListener;
import com.video.cut.widget.VideoTrimmerView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import VideoHandle.EpVideo;
import butterknife.BindView;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.OnMultiClickListener;
import itbour.onetouchshow.utils.AssetsDataUtils;
import itbour.onetouchshow.utils.DateUtils;
import itbour.onetouchshow.utils.FileUtils;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;
import itbour.onetouchshow.utils.compress.VideoCompress;

/**
 * Created by Administrator on 2018/7/5.
 */

public class VideoTimmerCutActivity extends MVPBaseActivity implements TrimVideoListener {

    static final int VIDEO_PLAY = 6;
    /**
     * 提供取消
     */
    public OSSAsyncTask task;
    /**
     * 视频宽高以及URL
     */
    @BindView(R.id.trimmer_view)
    VideoTrimmerView trimmerView;
    Handler UIHandler = new Handler();
    EpVideo epVideo;
    private OneToucDialog oneToucDialog;
    private String userType;
    private String localVideoUrl;
    private String videoPath;
    private VideoCompress.VideoCompressTask videoCompressTask;
    //QiNiu压缩出错时的保护
    private int mWidth;
    private int mHeight;
    private String mInputUrl;
    private String mOutPutPath;
    private int mRotate;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case VIDEO_PLAY:
                    dismissProgressDialog();
                    trimmerView.initVideoByURI(videoPath);
                    epVideo = new EpVideo(videoPath);
                    break;
            }
        }
    };

    public static Intent getLaunchIntent(Context context, String videoUrl, String userType) {
        Intent intent = new Intent(context, VideoTimmerCutActivity.class);
        intent.putExtra(AppConst.KEY_VIDEO_URL, videoUrl);
        intent.putExtra(AppConst.KEY_USER_TYPE, userType);
        return intent;
    }


    public static void startTimmer(final Context context, final String inputFile, final String outputFile, final long startMs, final long endMs, final TrimVideoListener callback) {
        if (callback != null) {
            callback.onStartTrim();
        }
        PLShortVideoTrimmer mShortVideoTrimmer = new PLShortVideoTrimmer(context, inputFile, outputFile);
        PLShortVideoTrimmer.TRIM_MODE mode = PLShortVideoTrimmer.TRIM_MODE.ACCURATE;//: PLShortVideoTrimmer.TRIM_MODE.ACCURATE
        mShortVideoTrimmer.trim(startMs, endMs, mode, new PLVideoSaveListener() {
            @Override
            public void onSaveVideoSuccess(String path) {
                callback.onFinishTrim(path);
            }

            @Override
            public void onSaveVideoFailed(final int errorCode) {
                // trim(context, inputFile, outputFile, startMs, endMs, callback);
            }

            @Override
            public void onSaveVideoCanceled() {
                if (callback != null)
                    callback.onCancel();
            }

            @Override
            public void onProgressUpdate(final float percentage) {
            }
        });
        //  mShortVideoTrimmer.cancelTrim();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_timmer_cut;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (trimmerView != null) {
            trimmerView.onVideoPause();
            trimmerView.setRestoreState(true);
            trimmerView.setOnTrimVideoListener(this);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        // showProgressDialogWithText();
        setTitleText("视频截取");
        getToolBarView().getRightTextView().setText("保存");
        getToolBarView().getRightTextView().setVisibility(View.VISIBLE);
        OnMultiClickListener.MIN_CLICK_DELAY_TIME = 4000;
        getToolBarView().getRightTextView().setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                getToolBarView().getRightTextView().setEnabled(false);
                //  showNewDialog("视频裁剪中...");
                showProgressDialogWithText("正在裁剪...");
                String newVideoPath = FileUtils.getDownloadDir() + DateUtils.getYMD() + ".mp4";
                trimmerView.onSaveClicked(newVideoPath);
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (trimmerView != null) {
            trimmerView.onCancelClicked();
        }
        if (videoCompressTask != null) {
            videoCompressTask.cancel(true);
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        if (trimmerView != null) {
            trimmerView.onDestroy();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        Bundle extras = getIntent().getExtras();
        String videoUrl = null;
        if (extras != null) {
            videoUrl = extras.getString(AppConst.KEY_VIDEO_URL);
            //分为直接裁剪添加
            //和  滤镜修改剪切
            userType = extras.getString(AppConst.KEY_USER_TYPE);
        }
        trimmerView.setOnTrimVideoListener(this);
        ///  if (videoUrl==null)return;
        if (videoUrl.startsWith("http") || videoUrl.startsWith("https")) {
            String localVideoUrl = SpUtils.getInstance().getString(videoUrl);
            if (TextUtils.isEmpty(localVideoUrl)) {
                AssetsDataUtils.doDonwloadVideo(videoUrl, new AssetsDataUtils.DownLoadVideoListener() {
                    @Override
                    public void onSuccess(String path) {
                        videoPath = path;
                        mHandler.sendEmptyMessage(VIDEO_PLAY);
                    }

                    @Override
                    public void onFail() {

                    }
                });
            } else {
                trimmerView.initVideoByURI(localVideoUrl);
                epVideo = new EpVideo(localVideoUrl);
            }
        } else {
            localVideoUrl = videoUrl;
            trimmerView.initVideoByURI(localVideoUrl);
            epVideo = new EpVideo(localVideoUrl);
        }
    }

    public void dismissDialog() {
        UIUtils.getHandler().post(new Runnable() {
            @Override
            public void run() {
                try {
                    if ((oneToucDialog != null) && oneToucDialog.isShowing()) {
                        oneToucDialog.dismiss();
                    }
                    dismissProgressDialog();
                } catch (final IllegalArgumentException e) {
                    // Handle or log or ignore
                } catch (final Exception e) {
                    // Handle or log or ignore
                } finally {
                    oneToucDialog = null;
                }
            }
        });


    }

    public void cliptAndSave() {
        String Video = ".mp4";
        String videoName = AliRequestUtils.getInstance().createFileName("video", App.getLoginBean().getUserInfo().getUserId() + "") + Video;
        String IMAGE = ".png";
        String imageName = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + IMAGE;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap videoThumbnail = ImageLoader.getInstance().getVideoThumbnail(localVideoUrl);
                    AliRequestUtils.getInstance().setName(imageName);
                    File imagefile = AliRequestUtils.getInstance().saveBitmapFile(videoThumbnail, FileUtils.getJpgFileName(localVideoUrl));
                    App.ossClient.putObject(AliRequestUtils.getInstance().putObjectRequest(imagefile.getAbsolutePath()));
                    String imagePathName = AppConfig.UPLOAD_ALYUN + imageName;
                    AliRequestUtils.getInstance().setName(videoName);
                    PutObjectRequest put = new PutObjectRequest(AppConst.OSSBUCKETNAME, videoName, localVideoUrl);
                    // 异步上传时可以设置进度回调
                    put.setProgressCallback((request, currentSize, totalSize) -> {
                        UIHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (oneToucDialog != null) {
                                    int progress = (int) (currentSize * 100 / totalSize);
                                    oneToucDialog.setTvprogress(progress + "% ");
                                    oneToucDialog.setDownloadProgress(progress);
                                }
                            }
                        });
                    });
                    task = App.ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                            T_.showToastReal("上传完成");
                            UIHandler.post(new Runnable() {
                                @Override
                                public void run() {

                                    if (trimmerView != null) {
                                        trimmerView.onCancelClicked();
                                        trimmerView.setOnTrimVideoListener(null);
                                        trimmerView.onDestroy();
                                    }

                                    String videoPathfile = AppConfig.UPLOAD_ALYUN + videoName;
                                    //存储本地路径和网络路径对应  网络路径对应本地路径
                                    SpUtils.getInstance().saveString(videoPathfile, localVideoUrl);
                                    if (userType.equals(UserMakeTag.ADDVIDEO.getTypeName())) {
                                        UserMakeTag userMakeTag = UserMakeTag.ADDVIDEO;
                                        userMakeTag.setTag(videoPathfile);
                                        userMakeTag.setTag1(imagePathName);
                                        UIUtils.getHandler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                EventBus.getDefault().post(userMakeTag);
                                                dismissDialog();
                                                finish();
                                            }
                                        }, 300);
                                    } else if (userType.equals(UserMakeTag.CUTUPDATE.getTypeName())) {
                                        UserMakeTag userMakeTag = UserMakeTag.CUTUPDATE;
                                        userMakeTag.setTag(videoPathfile);
                                        UIUtils.getHandler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                EventBus.getDefault().post(userMakeTag);
                                                dismissDialog();
                                                finish();
                                            }
                                        }, 300);
                                    }


                                }
                            });
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            // 请求异常
                            T_.showToastReal("上传失败");
                            if (clientExcepion != null) {
                                // 本地异常如网络异常等
                                clientExcepion.printStackTrace();
                                L_.e(clientExcepion.getMessage());
                            }
                            if (serviceException != null) {
                                serviceException.printStackTrace();
                                L_.e(serviceException.getMessage());
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    getToolBarView().getRightTextView().setEnabled(true);
                                    dismissDialog();
                                }
                            });

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    T_.showToastWhendebug("上传失败");
                    L_.e(e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            getToolBarView().getRightTextView().setEnabled(true);
                            dismissDialog();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    public void onStartTrim() {
        showProgressDialogWithText("正在裁剪");
    }

    public void showNewDialog(String userType) {
        try {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (oneToucDialog != null) {
                        oneToucDialog.dismiss();
                    }
                    OneToucDialog.Builder builder = new OneToucDialog.Builder(VideoTimmerCutActivity.this);
                    builder.content(userType);
                    oneToucDialog = builder.neutralText("取消").onNeutral(new OneToucDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(OneToucDialog dialog, DialogAction which) {
                            if (trimmerView != null) {
                                trimmerView.onCancelClicked();
                            }
                            if (videoCompressTask != null) {
                                videoCompressTask.cancel(true);
                            }
                            if (task != null) {
                                task.cancel();
                            }
                            getToolBarView().getRightTextView().setEnabled(true);
                        }
                    }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE_DOWNLOAD)
                            .cancelable(false).setShowDownloadProgress(true).setmWidth(AppConst.APP_DIALOG_WIDTH)
                            .show();
                    oneToucDialog.setDownloadProgress(1);
                    oneToucDialog.setTvprogress(1 + "% ");
                }
            });

        } catch (Exception e) {

        }
    }

    @Override
    public void onFinishTrim(String url) {
        localVideoUrl = url;
        dismissProgressDialog();
        showNewDialog("视频上传中...");
        cliptAndSave();
    }

    public void startVideoCompress(final Context context, final String inputFile, final String outputFile) {
    }

    private void startMediaCodeCompress(String inputPath, String outputPath, int width, int height, int bitrate) {
        videoCompressTask = VideoCompress.compressVideoWithBitRate(width, height, bitrate, inputPath, outputPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess() {
                localVideoUrl = outputPath;
                showNewDialog("视频上传中...");
                cliptAndSave();
            }

            @Override
            public void onFail() {
                getToolBarView().getRightTextView().setEnabled(true);
                T_.showToastReal("压缩失败");
                dismissDialog();
            }

            @Override
            public void onProgress(float percent) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (isFinishing()) {
                            return;
                        }
                        oneToucDialog.setTvprogress((int) percent + "% ");
                        oneToucDialog.setDownloadProgress((int) percent);
                    }
                });
            }
        });
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onFailed() {
        T_.showToastReal("剪切失败");
        getToolBarView().getRightTextView().setEnabled(true);
        if (trimmerView != null) {
            trimmerView.onCancelClicked();
        }
        dismissDialog();
    }

    @Override
    public void finish() {
        if (trimmerView != null) {
            trimmerView.onCancelClicked();
            trimmerView.setOnTrimVideoListener(null);
            trimmerView.onDestroy();
        }
        super.finish();
    }

}